import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

export interface CartItem {
  id: string;
  userId: string;
  productId: string; // 可以是门票ID或团购ID
  productType: 'ticket' | 'group-buy';
  quantity: number;
  addedAt: string;
}

@Injectable()
export class CartService {
  private readonly cartsFile = path.join(process.cwd(), 'data', 'carts.json');

  constructor() {
    const dataDir = path.join(process.cwd(), 'data');
    if (!fs.existsSync(dataDir)) {
      fs.mkdirSync(dataDir, { recursive: true });
    }

    if (!fs.existsSync(this.cartsFile)) {
      fs.writeFileSync(this.cartsFile, JSON.stringify([]));
    }
  }

  private readCarts(): CartItem[] {
    const data = fs.readFileSync(this.cartsFile, 'utf8');
    return JSON.parse(data);
  }

  private writeCarts(carts: CartItem[]): void {
    fs.writeFileSync(this.cartsFile, JSON.stringify(carts, null, 2));
  }

  findUserCart(userId: string): CartItem[] {
    const carts = this.readCarts();
    return carts.filter(item => item.userId === userId);
  }

  addToCart(userId: string, productId: string, productType: 'ticket' | 'group-buy', quantity: number = 1): CartItem {
    const carts = this.readCarts();
    
    // 检查是否已经存在相同的商品
    const existingItemIndex = carts.findIndex(
      item => item.userId === userId && 
              item.productId === productId && 
              item.productType === productType
    );
    
    if (existingItemIndex !== -1) {
      // 如果存在，则增加数量
      carts[existingItemIndex].quantity += quantity;
      carts[existingItemIndex].addedAt = new Date().toISOString();
    } else {
      // 如果不存在，则添加新项
      const newItem: CartItem = {
        id: Date.now().toString(),
        userId,
        productId,
        productType,
        quantity,
        addedAt: new Date().toISOString(),
      };
      carts.push(newItem);
    }
    
    this.writeCarts(carts);
    
    return carts[existingItemIndex !== -1 ? existingItemIndex : carts.length - 1];
  }

  updateCartItem(id: string, quantity: number): CartItem | null {
    const carts = this.readCarts();
    const index = carts.findIndex(item => item.id === id);
    
    if (index === -1) return null;
    
    if (quantity <= 0) {
      // 如果数量为0或负数，则删除该项
      carts.splice(index, 1);
    } else {
      carts[index].quantity = quantity;
      carts[index].addedAt = new Date().toISOString();
    }
    
    this.writeCarts(carts);
    return quantity > 0 ? carts[index] : null;
  }

  removeFromCart(id: string): boolean {
    const carts = this.readCarts();
    const initialLength = carts.length;
    const filteredCarts = carts.filter(item => item.id !== id);
    this.writeCarts(filteredCarts);
    return filteredCarts.length !== initialLength;
  }

  clearUserCart(userId: string): void {
    const carts = this.readCarts();
    const filteredCarts = carts.filter(item => item.userId !== userId);
    this.writeCarts(filteredCarts);
  }
}